package com.umeox.iqibla.azkar.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.umeox.iqibla.azkar.db.AppDatabase
import com.umeox.moto.common.executor.ThreadExecutor
import com.umeox.moto.common.log.Logger
import com.umeox.watch.moto.apiclient.model.ChantsCountDTO
import com.umeox.watch.moto.dataservice.DataProvider
import com.umeox.watch.moto.dataservice.constants.Constants
import com.umeox.watch.moto.dataservice.proxy.PullApiClientProxy

/**
 * Created by Rambo 2024/4/1/0001
 * Describe:
 */
class UnbindReceiver:BroadcastReceiver() {
    companion object  {
        const val ACTION_UPLOAD_CHANTS = "com.umeox.intent.action.UPLOAD_CHANTS"
    }


    override fun onReceive(context: Context?, intent: Intent?) {
        val action = intent?.action
        when(action){
            Constants.ACTION_UNBIND -> AppDatabase.get().azkarDao().deleteAll()

            ACTION_UPLOAD_CHANTS -> {
                if(!DataProvider.isActivated()){
                    return
                }
                ThreadExecutor.getInstance().io().execute {
                    //查询出所有没有上传的数据
                    val azkarDao = AppDatabase.get().azkarDao()
                    val notUploadAzkarList = azkarDao.loadNoUploadList()
                    notUploadAzkarList?.apply {
                        val chantsCountDTOList = mutableListOf<ChantsCountDTO>()
                        notUploadAzkarList.forEach {
                            val chantsCountDTO = ChantsCountDTO()
                            chantsCountDTO.date = com.umeox.moto.common.utils.DateUtils.formatDateTime(
                                it.todayMillis * 1000L,
                                "yyyyMMddZ"
                            )
                            chantsCountDTO.amount = it.count
                            chantsCountDTOList.add(chantsCountDTO)
                        }
                        if(chantsCountDTOList.isNotEmpty()){
                            val result = PullApiClientProxy.fetchBinder().uploadChants(chantsCountDTOList)
                            Logger.e(if(result) "赞念计数上传成功" else "赞念计数上传失败")
                            //更新本地数据库的上传标记为已上传
                            if(result){
                                notUploadAzkarList.forEach {
                                    it.isUpload = true
                                    azkarDao.save(notUploadAzkarList)
                                }
                            }
                        }
                    }
                }
            }
        }

    }
}